package net.hailxenu.stats;

import java.io.*;
import java.net.Socket;

public class ClientHandler implements Runnable
{
    // Net
    private Socket sock;
    private BufferedReader br;
    private BufferedWriter bw;
    private SqlHandler sql;

    // Misc.
    public String APIKey = "";

    public ClientHandler(Socket sock, SqlHandler sql)
    {
        try
        {
            this.sock = sock;
            this.br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            this.bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
            this.sql = sql;
        } catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public SqlHandler getSql()
    {
        return sql;
    }

    public boolean checkFileVersion(String hash)
    {
        return true;
        // TODO
    }

    public void run()
    {
        Logger.log(LT.INFO, "New Connection: " + sock.getRemoteSocketAddress().toString());

        String fileVersion = "";
        try
        {
            String auth = br.readLine();
            
            if(!auth.toLowerCase().startsWith("auth"))
            {
                sock.close();
                return;
            }
            
            APIKey = auth.toLowerCase().replace("auth", "").trim();
            APIKey = APIKey.substring(0, APIKey.indexOf(" "));

            if(APIKey.length() != 32 && sql.read("SELECT * FROM `servers` WHERE `apikey`='" + APIKey + "' LIMIT 1").next() == false)
            {
                sock.close();
                return;
            }

            fileVersion = auth.toLowerCase().replace("auth " + APIKey + " ", "").trim();
            if(!checkFileVersion(fileVersion))
            {
                sock.close();
                return;
            }

        } catch(Exception e){ Logger.log(LT.WARNING, e.getMessage()); return; }

        Logger.log(LT.INFO, "Successful Authentication.\nAPI Key: " + APIKey + "\nFile Version: " + fileVersion);

        String input, id = "";
        Packet p;
        try{
            while(!sock.isClosed() && (input = br.readLine()) != null)
            {
                if(!input.contains(":") && !input.startsWith("startupdate"))
                {
                    Logger.log(LT.INFO, "Invalid packet format: " + input);
                }else{
                    id = input.split(":")[0];
                    input = input.replace(id+":", "");
                    p = new Packet(this, input, id);
                    if(p.run())
                    {
                        //Logger.log(LT.INFO, "Updated info.");
                    }else
                    {
                        Logger.log(LT.INFO, "Error while updating info.");
                    }
                    
                }
            }
        }catch(Exception e){ Logger.log(LT.WARNING, e.getMessage()); }
    }
}
